<template>
  <div class="supplier-manage">
    <ListTab v-model="activeTab" :tabs="supplierTabs" :show-header="!showMobilePage" is-table @tabClick="getList(true)" />
    <div :class="{'mobile-table mobile-pt mobile-min-height':showMobilePage}" class="table-list min-fill-page">
      <div v-if="!showMobilePage" style="position:relative;margin-bottom:16px;">
        <FilterInput
          ref="FilterToolRef"
          v-model="filterForm"
          :filter-list="filterList"
          show-search-btn
          is-show-config
          @handelClick="queryClick"
          @queryEmpty="queryEmpty"
          @filterTagStatus="filterTagStatus"/>
        <div class="opeator-bar-checkbox">
          <el-checkbox v-model="isExamine" @change="queryClick">已审批</el-checkbox>
        </div>
        <div class="opeator-bar">
          <ManageTop :fetch-data="getList" @create="handleCreate" />
        </div>
      </div>
      <el-row
        v-loading="listLoading"
        element-loading-custom-class="supplier-loading-text"
        style="min-height: 300px">
        <u-table
          v-if="list.total > 0"
          :data="list.items"
          :height="setTableHeight"
          :row-height="rowHeight()"
          :border="true"
          beautify-table
          header-drag-style
          use-virtual
          element-loading-text="加载中..."
          empty-text="暂无数据"
          header-cell-class-name="order-data-header-cell"
          fit
          hightlight-current-row
          class="fb-table"
          @sort-change="sortMethod">
          <u-table-column align="left" label="供应商编号" min-width="140">
            <template slot-scope="scope">
              <el-tooltip v-if="scope.row.supplierCode" placement="top-start" effect="dark">
                <div slot="content" style="max-width:200px;">{{ scope.row.supplierCode }}</div>
                <div class="ellipsis" style="color:#406EFF; cursor: pointer" @click="btnCheck(scope)">{{ scope.row.supplierCode }}</div>
              </el-tooltip>
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="供应商名称" width="240">
            <template slot-scope="scope">
              <el-tooltip v-if="scope.row.supplier" placement="top-start" effect="dark">
                <div slot="content" style="max-width:200px;">
                  {{ scope.row.supplier || '--' }}
                </div>
                <div class="ellipsis">{{ scope.row.supplier || '--' }}</div>
              </el-tooltip>
              <div v-else class="ellipsis">{{ scope.row.supplier || '--' }}</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="供应商类型" width="100">
            <template slot-scope="scope">
              <div slot="content" style="max-width:200px;">
                {{ scope.row.supplierType ? scope.row.supplierType === '0' ? '个人' : '公司' : '--' }}
              </div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="总订单数" min-width="130" prop="orderNum">
            <template slot-scope="scope">
              <div v-if="scope.row.orderNum || scope.row.orderNum === 0">{{ scope.row.orderNum }}</div>
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="待结订单" min-width="130" prop="notSupplierNum">
            <template slot-scope="scope">
              <div v-if="scope.row.notSupplierNum || scope.row.notSupplierNum === 0">{{ scope.row.notSupplierNum }}</div>
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="总成本数" min-width="130" prop="costNum">
            <template slot-scope="scope">
              <div v-if="scope.row.costNum || scope.row.costNum === 0">{{ scope.row.costNum }}</div>
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="待结订单成本" width="130" prop="notOrderCostNum">
            <template slot-scope="scope">
              <div v-if="scope.row.notOrderCostNum || scope.row.notOrderCostNum === 0">{{ scope.row.notOrderCostNum }}</div>
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="待结成本" min-width="150" prop="notCostNum">
            <template slot="header" slot-scope="scope">
              <div class="table-header">
                <div class="flex">
                  <span class="label">{{ scope.column.label }}</span>
                  <tipIcon content="仅统计未关联订单的成本"/>
                </div>
              </div>
            </template>
            <template slot-scope="scope">
              <div v-if="scope.row.notCostNum || scope.row.notCostNum === 0">{{ scope.row.notCostNum }}</div>
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="资源关联数" min-width="120" prop="linkResource">
            <template slot-scope="scope">
              <div v-if="scope.row.linkResource || scope.row.linkResource === 0">{{ scope.row.linkResource }}</div>
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="标签" width="150">
            <template slot-scope="scope">
              <TagSelect v-model="scope.row.tag" mode="list" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="费率" width="90">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.priceRate"/>
            </template>
          </u-table-column>
          <u-table-column align="left" label="所属部门">
            <template slot-scope="scope">
              <el-tooltip v-if="scope.row.departmentName" class="item" placement="top" effect="dark">
                <div slot="content" style="max-width: 200px;">{{ scope.row.departmentName }}</div>
                <div class="remark ellipsis">{{ scope.row.departmentName }}</div>
              </el-tooltip>
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="可抵扣税率" min-width="130">
            <template slot-scope="scope">
              <div v-if="scope.row.deductionRate || scope.row.deductionRate === 0">{{ scope.row.deductionRate }}%</div>
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="创建人">
            <template slot-scope="scope">
              <CheckUserInfo :user-id="scope.row.createUserId" :label="scope.row.createUser" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="创建时间" width="110" prop="createTime" sortable="custom">
            <template slot-scope="scope">
              <div>{{ scope.row.createTime | format('YYYY/MM/DD') }}</div>
            </template>
          </u-table-column>
          <u-table-column :width="showMobilePage ? 50 : 125" align="left" label="操作" fixed="right">
            <template slot-scope="scope">
              <div v-if="!showMobilePage" class="button-container">
                <div class="button-text" @click="btnCheck(scope)">查看</div>
                <!-- (scope.row.notSupplierNum || scope.row.notCostNum) -->
                <el-dropdown
                  v-if="hasRouteAuth('medium:supplierAudit:launch')"
                  trigger="click">
                  <div class="button-text border">结算</div>
                  <el-dropdown-menu slot="dropdown" style="padding:0;">
                    <el-dropdown-item style="width:130px;padding:0;text-align:center;" @click.native="settlement(scope, 0)">
                      <div>订单成本付款结算</div>
                    </el-dropdown-item>
                    <el-dropdown-item style="width:130px;padding:0;text-align:center;" @click.native="settlement(scope, 1)">
                      <div>其他付款结算(非订单)</div>
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
                <div v-else class="button-text border" style="color: #bbb; cursor: default">结算</div>
                <div class="button-text border" @click="handleSupplierDel(scope.row.id)">删除</div>
              </div>
              <tableOperateBtn v-else :is-hide-on-click="false">
                <el-dropdown-item @click.native="btnCheck(scope)">
                  <div>查看</div>
                </el-dropdown-item>
                <el-dropdown-item v-if="hasRouteAuth('medium:supplierAudit:launch')">
                  <el-dropdown :hide-on-click="false">
                    <div style="font-size: 14px;">结算</div>
                    <el-dropdown-menu slot="dropdown" style="padding:0;">
                      <el-dropdown-item style="width:130px;padding:0;text-align:center;" @click.native="settlement(scope, 0)">
                        <div>订单成本付款结算</div>
                      </el-dropdown-item>
                      <el-dropdown-item style="width:130px;padding:0;text-align:center;" @click.native="settlement(scope, 1)">
                        <div>其他付款结算(非订单)</div>
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                </el-dropdown-item>
                <el-dropdown-item v-else>
                  <div style="color: #bbb; cursor: default">结算</div>
                </el-dropdown-item>
                <el-dropdown-item @click.native="handleSupplierDel(scope.row.id)">
                  <div>删除</div>
                </el-dropdown-item>
              </tableOperateBtn>
            </template>
          </u-table-column>
        </u-table>
        <empty-placeholder v-else-if="!isInit" style="margin-bottom: 24px" />
      </el-row>
      <el-row v-if="showMobilePage" type="flex" justify="left">
        <el-pagination
          v-show="list.total > 0"
          :current-page.sync="list.page"
          :page-size="list.perPage"
          :total="list.total"
          :small="true"
          :page-sizes="[20, 50, 100, 250, 500]"
          :layout="pageLayout"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-row>
      <fixed-pagination v-if="list.total > 0 && !showMobilePage || showMobilePage">
        <template v-if="showMobilePage">
          <FilterInput ref="FilterToolRef" v-model="filterForm" :filter-list="filterList" show-mobile-icon show-search-btn is-show-config @handelClick="queryClick" @queryEmpty="queryEmpty" @filterTagStatus="filterTagStatus">
            <div slot="checkGroup">
              <el-checkbox v-model="isExamine" @change="queryClick">已审批</el-checkbox>
            </div>
          </FilterInput>
          <ManageTop :fetch-data="getList" :is-mobile="showMobilePage" @create="handleCreate" />
        </template>
        <template v-else>
          <div v-if="timeDiff >= 60">
            <el-tooltip :open-delay="800" placement="top">
              <div slot="content" style="max-width: 200px;">统计数据预计5分钟内完成更新，刷新页面后可查看最新数据</div>
              <div class="update-time"><img :src="cacheTimeIcon" alt=""> 列表统计数据更新时间：{{ cacheTime | format('YYYY/MM/DD HH:mm') }}</div>
            </el-tooltip>
          </div>
          <div style="flex:1"/>
          <el-pagination
            v-show="list.total > 0"
            :current-page="list.page"
            :page-size="list.perPage"
            :total="list.total"
            :page-sizes="[20, 50, 100, 250, 500]"
            layout="total, prev, pager, next, sizes, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </template>
      </fixed-pagination>
    </div>
    <CreateDialog ref="createRef" @refresh="getList" />
  </div>
</template>
<script>
import { supplierManageList, supplierManageDelete, getBusinessType } from '@/api/supplier';
import ManageTop from '@/components/SupplierComponent/manageTop';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import Title from '@/components/Title';
import CreateDialog from './create/create';
import selectWithoutHttp from '@/components/Common/selectWithoutHttp';
import TagSelect from '@/components/Common/tagSelect';
import clearIcon from '@/assets/medium/clear.png';
import setting from '@/assets/setting.png';
import cacheTimeIcon from '@/assets/cacheTime.png';
import { format } from '@/filters/date';
import { hasRouteAuth } from '@/utils/permission';
import ListTab from '@/components/ListTab';
import { mapState } from 'vuex';
import TableAdaptive from '@/mixins/tableAdaptive';
import { showModal } from '@/utils/message';
import { getDepartmentAll, getTagAll } from '@/api/config';
import { platformList } from '@/api/select';
import { getOperateoptions } from '@/api/resource';
import { allRegionData } from '@/utils/areaConfig';
import { TAG_MODULES } from '@/utils/const';
import { paramsRangeFormat, paramsAryToStr } from '@/utils/paramsFormat';
import mobileTable from '@/mixins/mobileTable';

export default {
  filters: {
    format
  },
  components: { ManageTop, Title, EmptyPlaceholder, selectWithoutHttp, ListTab, CreateDialog, TagSelect },
  mixins: [TableAdaptive, mobileTable],
  data() {
    return {
      TAG_MODULES,
      clearIcon, cacheTimeIcon,
      setting,
      activeTab: -1,
      filterForm: {
        supplier: '',
        resource: ''
      },
      isExamine: false,
      sortName: '',
      sortType: '',
      list: {},
      listLoading: false,
      perPage: 20,
      curPage: 1,
      deptTreeList: [],
      cacheTime: '',
      orderPlatformOption: [],
      operateModeList: [],
      tagTreeList: [],
      businessTypeOptions: [],
      isSignUpOption: [
        { value: 1, label: '是' },
        { value: 0, label: '否' }
      ],
      rangeKeyArr: [
        { attr: 'signPoint', start: 'signPointStart', end: 'signPointEnd', type: 'number' },
        { attr: 'signStartDate', start: 'signStartDateStart', end: 'signStartDateEnd', type: 'round', addTime: true },
        { attr: 'signEndDate', start: 'signEndDateStart', end: 'signEndDateEnd', type: 'round', addTime: true },
        { attr: 'createTime', start: 'createTimeStart', end: 'createTimeEnd', type: 'round', addTime: true }
      ],
      arrayKeyArr: ['region', 'tag', 'currentNode', 'businessType'],
      isInit: true
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo
    }),
    filterList() {
      return [
        { keyword: 'supplier', name: '供应商名称', type: 'input' },
        { keyword: 'supplierCode', name: '供应商编号', type: 'input' },
        { keyword: 'agentName', name: '签单签约经纪', type: 'input' },
        { keyword: 'resource', name: '账号', type: 'input' },
        { keyword: 'signPoint', name: '签约积分', type: 'inputRange', startPlaceholder: '开始', endPlaceholder: '结束' },
        { keyword: 'createName', name: '创建人', type: 'input' },

        { keyword: 'departmentId', name: '所属部门', type: 'cascaderSelect', childrenVal: 'children', options: this.deptTreeList },
        { keyword: 'cooperationStatus', name: '合作状态', type: 'select', options: [{ value: 0, label: '正常合作' }, { value: 1, label: '终止合作' }] },
        { keyword: 'publishedStatus', name: '刊例状态', type: 'select', options: [
          { value: 0, label: '正常上刊' }, { value: 1, label: '解约下刊' }, { value: 2, label: '处罚停刊' }
        ] },
        { keyword: 'cooperationMode', name: '合作模式', type: 'select', options: [
          { value: 1, label: '广告代理' }, { value: 2, label: '演艺经纪' }, { value: 3, label: '商务约' },
          { value: 4, label: '内容约' }, { value: 5, label: '孵化约' }, { value: 6, label: '其他' }
        ] },
        { keyword: 'cooperationType', name: '合作性质', type: 'select', options: [
          { value: 0, label: '独家' }, { value: 1, label: '非独家' }
        ] },
        { keyword: 'orderPlatformId', name: '下单平台', type: 'select', options: this.orderPlatformOption },
        {
          keyword: 'operatingModelId', name: '运营模式', valueName: 'value', labelName: 'label',
          childrenVal: 'children', type: 'cascaderSelect', options: this.operateModeList
        },
        { keyword: 'microtask', name: '是否挂靠', type: 'select', options: [{ value: 0, label: '否' }, { value: 1, label: '是' }] },
        { keyword: 'sex', name: '性别', type: 'select', options: [{ value: 0, label: '男' }, { value: 1, label: '女' }] },
        {
          keyword: 'region', name: '地域', valueName: 'label', labelName: 'label', checkStrictly: false, separator: '-',
          childrenVal: 'children', type: 'cascaderSelect', options: allRegionData, emitPath: true, filterable: true
        },
        {
          keyword: 'businessType', name: '行业类别', valueName: 'id', labelName: 'name', type: 'mulSelect', options: this.businessTypeOptions
        },
        { keyword: 'tag', name: '标签', valueName: 'name', labelName: 'name',
          childrenVal: 'item', type: 'cascaderSelect', checkStrictly: false, options: this.tagTreeList,
          multiple: true, filterable: true, collapseTags: true
        },
        { keyword: 'isSignUp', name: '是否签约', type: 'select', options: this.isSignUpOption },
        { keyword: 'signStartDate', name: '签约起始日期', timeType: 'daterange', type: 'rangeDate' },
        { keyword: 'signEndDate', name: '签约结束日期', timeType: 'daterange', type: 'rangeDate' },
        { keyword: 'createTime', name: '创建日期', timeType: 'daterange', type: 'rangeDate' }
      ];
    },
    timeDiff() {
      const updateTime = this.cacheTime;
      const isS = updateTime.toString().length === 10;
      if (!updateTime) return 0;
      let time = Date.parse(new Date());
      if (isS) {
        time = Math.round(time / 1000);
      }
      const ans = time - Number(updateTime);
      return isS ? ans : Math.round(ans / 1000);
    },
    supplierTabs() {
      return [
        { id: -1, name: '全部' },
        { id: 1, name: '公司' },
        { id: 0, name: '个人' }
      ];
    }
  },
  beforeRouteEnter(to, from, next) {
    to.meta.isChange = from.name === 'supplierDetail' || from.name === 'supplierManageAdd';
    next();
  },
  activated() {
    if (this.$route.meta.isChange) {
      this.getList();
    } else {
      const hasDefaultPresetFilter = this.$refs.FilterToolRef && this.$refs.FilterToolRef.hasDefaultPresetFilter;
      // 当预设的默认筛选且为第一次进入页面时，不请求数据（会在 filterTool 组件进行筛选）
      if (!this.isInit || !hasDefaultPresetFilter) {
        this.getList(false);
      }
    }
    const { toCreate, customerId } = this.$route.query;
    if (toCreate) {
      this.handleCreate();
      // 从客户默认回填部分信息新建
      customerId && this.syncFromCustomer(customerId);
      this.$router.replace({ name: 'supplierManage' });
    }
    this.getBusinessTypeOptions();
    this.queryDeptTreeList();
    this.platformList();
    this.getOperateoptionsData();
    this.queryTagTreeList();
  },
  methods: {
    hasRouteAuth,
    // 获取部门列表
    queryDeptTreeList() {
      getDepartmentAll().then(res => {
        this.deptTreeList = (res && res.data) || [];
      }).catch(e => {
        console.log(e);
      });
    },
    handleCreate() {
      this.$refs['createRef'].init();
    },
    syncFromCustomer(id) {
      this.$refs['createRef'].syncFromCustomer(id);
    },
    formatParams() {
      const filterForm = JSON.parse(JSON.stringify(this.filterForm));
      const params = {
        page: this.curPage,
        perPage: this.perPage,
        sortName: this.sortName,
        sortType: this.sortType,
        supplierType: this.activeTab,
        isExamine: this.isExamine,
        ...filterForm
      };
      paramsRangeFormat(this.rangeKeyArr, params);
      paramsAryToStr(this.arrayKeyArr, params);
      delete params.signPoint;
      delete params.signStartDate;
      delete params.signEndDate;
      delete params.createTime;
      return params;
    },
    getList(isReset = true) {
      isReset && (this.curPage = 1);
      const params = this.formatParams();
      this.listLoading = true;
      supplierManageList(params).then(res => {
        this.isInit = false;
        if (res.data && res.data.items && res.data.items[0] && res.data.items[0].cacheTime) {
          this.cacheTime = res.data.items[0].cacheTime;
        }
        this.list = res.data;
        this.listLoading = false;
      }).catch(err => console.error(err)).finally(() => {
        this.listLoading = false;
      });
    },
    queryClick() {
      this.getList();
    },
    queryEmpty() {
      this.filterForm = {};
      this.isExamine = false;
      this.getList();
    },
    btnCheck(scope) {
      this.$router.push({
        name: 'supplierManageDetail',
        params: { id: scope.row.id }
      });
    },
    settlement(scope, type) {
      const query = { id: scope.row.id, from: 'saleSupplier' };
      if (type === 1) query.isNotOrder = 1;
      if (type === 2) query.isInvite = 1;
      this.$router.push({
        name: 'supplierCreate', // supplierCreate\supplierDetail
        query
      });
    },
    sortMethod(a) {
      if (a.order) {
        this.sortName = a.prop;
        this.sortType = a.order === 'ascending' ? 1 : -1;
      } else {
        this.sortName = '';
        this.sortType = '';
      }
      this.getList(false);
    },
    handleSupplierDel(id) {
      showModal('请确认是否删除', '', {}).then(() => {
        supplierManageDelete(id).then(() => {
          this.$message.success('删除成功');
          this.getList(false);
        });
      });
    },
    handleSizeChange(perPage) {
      this.perPage = perPage;
      this.getList();
    },
    handleCurrentChange(page) {
      this.curPage = page;
      this.getList(false);
    },
    // 下单平台
    async platformList() {
      try {
        const result = await platformList();
        result.data = result.data.map(item => {
          item = {
            value: item.id,
            label: item.value
          };
          return item;
        });
        result.data.unshift({ value: -2, label: '--' });
        this.orderPlatformOption = result.data;
      } catch (error) {
        console.log(error);
      }
    },
    queryTagTreeList() {
      const params = { type: this.TAG_MODULES.SETTLE_SUPPLIER };
      getTagAll(params).then(res => {
        this.tagTreeList = (res && res.data) || [];
        this.tagTreeList.forEach(item => {
          if (!item.item) item.disabled = true;
        });
      }).catch(e => {
        console.log(e);
      });
    },
    // 获取运营模式
    getOperateoptionsData() {
      getOperateoptions().then(res => {
        this.operateModeList = res.data;
      });
    },
    getBusinessTypeOptions() {
      getBusinessType().then(res => {
        if (res.code === 200) {
          this.businessTypeOptions = res.data;
        }
      }).catch(error => console.error(error));
    }

  }
};
</script>
<style lang="scss" scoped>
.supplier-manage {
  .table-list {
    margin: 16px 16px 0 16px;
    background-color: #fff;
    padding: 20px 20px 55px 20px;
  }
  &::v-deep {
    .supplier-loading-text {
      .el-loading-text {
        position: relative;
        //&::after {
        //  content: '首次加载较慢，请耐心等待';
        //  display: block;
        //}
      }
    }
  }
}
.table-header {
  display: inline-block;
  .flex {
    display: flex;
    align-items: center;
  }
}
.opeator-bar {
  position: absolute;
  right: 0;
  top: 0;
  display: flex;
  align-items: center;
}
.opeator-bar-checkbox {
  position: absolute;
  left: 509px;
  top: 6px;
  display: flex;
  align-items: center;
}
.button-container {
  display: flex;
  .border {
    display: block;
    padding-left:6px;
    margin-left: 6px;
    position: relative;
    &::before {
      content: '';
      position: absolute;
      left: 0;
      top: 50%;
      margin-top: -7px;
      width: 1px;
      background: #ddd;
      height: 14px;
    }
  }
}
.update-time {
  font-size: 12px;
  font-weight: 400;
  line-height: 14px;
  color: #666666;
  display: flex;
  align-items: center;
  img {
    width: 12px;
    margin-right: 5px;
  }
}
.supplier-num {
  color: #406EFF;
}
.mobile-table {
  ::v-deep .mobile-pagination {
    .more-opeator {
      margin-left: 24px !important;
    }
  }
}
</style>
